package com.house.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.house.common.Result;
import com.house.entity.House;
import com.house.service.HouseService;
import com.house.util.ResultUtil;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author asus
 * @since 2021-02-28
 */
@RestController
@RequestMapping("/house")
public class HouseController {
    @Resource
    private HouseService houseService;

    @Value("${prop.house-upload-folder}")
    private String HOUSE_UPLOAD_FOLDER;

    @GetMapping("selectHousesByHousePrice")
    public Result selectHousesByHousePrice(BigDecimal startPrice, BigDecimal endPrice) {
        List<House> houseList = new ArrayList<>();

        houseList = houseService.selectHousesByHousePrice(startPrice, endPrice);

        return houseList != null ? ResultUtil.success(201, houseList) : ResultUtil.failure(501, null);
    }

    @GetMapping("selectHousesByHouseArea")
    public Result selectHousesByHouseArea(Integer minArea, Integer maxArea) {
        List<House> houseList = new ArrayList<>();

        houseList = houseService.selectHousesByHouseArea(minArea, maxArea);

        return houseList != null ? ResultUtil.success(201, houseList) : ResultUtil.failure(501, null);
    }

    @GetMapping("selectHousesByHouseTypeRoomNumAndHallName")
    public Result selectHousesByHouseTypeRoomNumAndHallName(Integer roomNum, Integer hallNum) {
        List<House> houseList = new ArrayList<>();

        houseList = houseService.selectHousesByHouseType(roomNum, hallNum, null, null);

        return houseList != null ? ResultUtil.success(201, houseList) : ResultUtil.failure(501, null);
    }

    @GetMapping("SelectHousesByHouseTypeMaleNumAndFemaleNum")
    public Result selectHousesByHouseTypeMaleNumAndFemaleNum(Integer maleNum, Integer femaleNum) {
        List<House> houseList = new ArrayList<>();

        houseList = houseService.selectHousesByHouseType(null, null, maleNum, femaleNum);

        return houseList != null ? ResultUtil.success(201, houseList) : ResultUtil.failure(501, null);
    }

    @GetMapping("/selectHouseByRoomNumAndHousePriceAndCentType/{roomNum}/{rentType}/{housePrice}/{pageNum}")
    public Result selectHouseByHouseTypeAndHousePriceAndCentType(@PathVariable("roomNum") Integer roomNum, @PathVariable("rentType") Integer rentType, @PathVariable("housePrice") Integer housePrice, @PathVariable("pageNum") Integer pageNum)
    {
        PageHelper.startPage(pageNum, 5);
        List<House> houseList = houseService.selectHouseByHouseTypeAndHousePriceAndCentType(roomNum, rentType, housePrice);
        PageInfo<House> pageInfo = new PageInfo<>(houseList);
        if(pageInfo != null)
        {
            return ResultUtil.success(201, pageInfo);
        }
        return ResultUtil.failure(501, "查询失败");
    }

    @GetMapping("SelectAllHouses/{pageNum}")
    public Result selectAllHouses(@PathVariable("pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum, 5);
        List<House> houseList = houseService.selectAllHouse();
        PageInfo<House> pageInfo = new PageInfo<>(houseList);

        if (pageInfo != null) {
            return ResultUtil.success(201, pageInfo);
        }

        return ResultUtil.failure(501, null);

    }

    @GetMapping("SelectHouseByHouseId/{houseId}")
    public Result selectHouseByHouseId(@PathVariable("houseId") Integer houseId) {
        House house = houseService.selectHouseByHouseId(houseId);

        if (house != null) {
            return ResultUtil.success(201, house);
        }
        return ResultUtil.failure(501, null);
    }

    @PostMapping("insertOneHouse")
    public Result saveOneHouseInfo(@RequestBody House house)
    {
        Integer index = houseService.insertOneHouse(house);
        if(index == 1)
        {
            return ResultUtil.success(202, index);
        }
        return ResultUtil.failure(502, "插入失败");
    }


    @PostMapping(value = "/uploadHousePic")
    public Result uploadHousePic(@RequestPart("file") MultipartFile file, @RequestParam("houseId") Integer houseId, HttpServletRequest request){
        if (file == null) {
            return ResultUtil.failure(0, "上传图片不能为0个", null);
        }
        if (file.getSize() > 1024 * 1024 * 10) { return ResultUtil.failure(0, "文件大小不能大于10M", null); }

        String savePath = HOUSE_UPLOAD_FOLDER + houseId + "/";
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }

        String filename = System.currentTimeMillis() + ".png";
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failure(0, "保存文件异常", null);
        }
        //返回文件名称
        return ResultUtil.success(300, filename);
    }

    @PostMapping(value = "/upload")
    public Result upload(@RequestPart("files") List<MultipartFile> multipartFiles, @RequestParam("houseId") Integer houseId, HttpServletRequest request) {
        String housePhotos = houseService.selectHouseByHouseId(houseId).getHousePhotos();
        List<String> pathNameList;
        if (housePhotos != null)
        {
            pathNameList = new ArrayList<>(Arrays.asList(housePhotos.split(",")));
        } else {
            pathNameList = new ArrayList<>();
        }

        if (multipartFiles.size() == 0) {
            return ResultUtil.failure(0, "上传图片不能为0个", null);
        }
        for (MultipartFile file : multipartFiles) {
            if (file.getSize() > 1024 * 1024 * 10) {
                return ResultUtil.failure(0, "文件大小不能大于10M", null);
            }
        }

        String savePath = HOUSE_UPLOAD_FOLDER + houseId + "/";

        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        for (MultipartFile file : multipartFiles)
        {
            String filename = System.currentTimeMillis() + ".png";
            pathNameList.add(filename);
            try {
                //将文件保存指定目录
                file.transferTo(new File(savePath + filename));
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.failure(0, "保存文件异常", null);
            }
        }
        System.out.println(pathNameList.toString());
        if (pathNameList.get(0).equals(""))
        {
            pathNameList.remove(0);
        }
        String pathNameStream = pathNameList.stream()
                                            .collect(Collectors.joining(","));
        houseService.updateHousePictures(houseId, pathNameStream);
        //返回文件名称
        return ResultUtil.success(206, multipartFiles.size());
    }

    @GetMapping("/selectHasReleaseHouseByReleaseId/{releaseId}")
    public Result selectHasReleaseHouseByReleaseId(@PathVariable("releaseId") Integer releaseId)
    {
        List<Integer> list = houseService.selectHasReleaseHouseId(releaseId);
        if(list == null)
        {
            return ResultUtil.failure(501, "查询失败");
        }else{
            return ResultUtil.success(201, list);
        }
    }

    @GetMapping("selectHouseByReleaseId/{releaseId}/{pageNum}")
    public Result selectHouseByReleaseId(@PathVariable("releaseId") Integer releaseId, @PathVariable("pageNum") Integer pageNum)
    {
        PageHelper.startPage(pageNum,6);
        List<House> houseList = houseService.selectHouseByReleaseId(releaseId);
        PageInfo<House> pageInfo = new PageInfo<>(houseList);
        if(pageInfo == null)
        {
            return ResultUtil.failure(501, "查询失败");
        }else{
            return ResultUtil.success(201, pageInfo);
        }
    }

    @GetMapping("selectHousesByHousePlace/{housePlace}")
    public Result selectHousesByHousePlace(@PathVariable("housePlace") String housePlace) {
        List<House> houseList = houseService.selectHousesByHousePlace(housePlace);
        if(houseList != null)
        {
           return ResultUtil.success(201, houseList);
        }
        return ResultUtil.failure(501, "查询失败");
    }

    @PostMapping("deleteOneHouse")
    public Result deleteOneHouse(@RequestParam("houseId") Integer houseId) {
        int res = houseService.deleteOneHouse(houseId);
        if(res == 1)
        {
            return ResultUtil.success(205, res);
        }
        return ResultUtil.failure(505,"删除失败");
    }

    @PostMapping("updateOneHouse")
    public Result updateOneHouse(@RequestBody House house){
        Integer index = houseService.updateOneHouse(house);
        if(index == 1) {
            return ResultUtil.success(207, "更新成功");
        }
        return ResultUtil.failure(507, "更新失败");
    }
}
